import http from "http";
import methods from "methods";
import Router from "./router/index.js";

function Application() {
  this.router = new Router();
}
Application.prototype.listen = function (...args) {
  const server = http.createServer((req, res) => {
    function done() {
      // 如果路由系统中的层不存在则调用此方法来结束响应
      res.end(`Cannot ${req.method} ${req.url}`);
    }
    // 交给路由系统来做匹配，如果匹配不到就调用done
    this.router.handle(req, res, done);
  });
  server.listen(...args);
};
methods.forEach((method) => {
  Application.prototype[method] = function (path, handler) {
    // 让路由系统处理逻辑
    this.router[method](path, handler);
  };
});

export default Application;
